<?php
/**
 * 订单模块Api Service
 *
 * 订单模块Api Service的注意及说明
 * 以下use模块请不要互相伤害
 *
 * @author    xiecz <xiecz@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\Order;
use Log, Session;
use Carbon\Carbon;
// use App\Model\Orders;
use App\Services\Tool\DataBase\SQL;
use App\Services\Tool\GeneralTool;
use App\Services\Tool\Order\OrderTool;
use App\Services\Coupons\CouponsService;
use App\Services\Tool\Order\AfterTool;
use App\Services\Tool\ExpressTool;
// use App\Services\Tool\DataBase\DB_MYSQL_XCZ;
use App\Jobs\CreateOrderPush;


class OrderApi{

    function __construct(OrderTool $orderTool,
                         CouponsService $couponsService,
                         ExpressTool $express){
        $this->orderTool      = $orderTool;
        $this->couponsService = $couponsService;
        $this->express        = $express;
    }

    /**
     * [生成订单(购物车)]
        参数：
            user_id         用户编号
            address_id      收货地址编号
            coupon_id       优惠券编号
            platform        平台 IOS Android Web
            message         备注
     */
    function create_order_by_shop_car($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||
            !isset($input['platform']))
            return GeneralTool::createResult('','M00002');

        if(isset($input['message']) && GeneralTool::getcode($input['message']) == '') return GeneralTool::createResult('','M05008');

        //判断用户是否存在
        if(!$this->orderTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        try{
            if(!isset($input['address_id'])) return GeneralTool::createResult('', 'M05072');
            $address = $this->orderTool->addressByID($input['address_id'],$input['user_id']);

            if(!isset($address['result'])||!isset($address['result']->consignee)) return GeneralTool::createResult('','M05006');

            //获取购物车商品详情
            $shop_car = $this->orderTool->get_shop_car_goods($input);
            if(!isset($shop_car['goods'])||!isset($shop_car['goods']['vaild'])||count($shop_car['goods']['vaild'])==0)
                return GeneralTool::createResult('','M05007');

            $coupon = isset($input['coupon_id']) && $input['coupon_id'] != '' ? $this->couponsService->getCouponInfoByShopCar($input) : [];
            if(isset($input['coupon_id']) && $input['coupon_id'] != '' && !isset($coupon['discount'])) return GeneralTool::createResult('','M05017');

            if(isset($shop_car['total_fee']) && isset($coupon['discount']) && is_numeric($coupon['discount']))
                $shop_car['total_fee'] -= $coupon['discount'];

            //生成订单
            $result = $this->orderTool->create_order($shop_car,$input,$address,$coupon);

            if($result['state'] == 'M00000') dispatch((new CreateOrderPush($shop_car, $result, $input))->delay(Carbon::now()->addMinutes(1)));

            return $result;

        }catch(\Exception $e){
            Log::info($e);
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        立即购买生成订单
        参数:
            user_id         用户编号
            product_id      作品编号
            colour_name     颜色编号
            size_name       尺码
            quantity        数量
            address_id      收货地址编号
            coupon_id       优惠券编号
            platform        平台 IOS Android Web
            message         备注

     */
    function create_order_by_buy_immediately($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||
            !isset($input['product_id'])||
            !isset($input['colour_name'])||
            !isset($input['size_name'])||
            !isset($input['quantity'])||
            !isset($input['address_id'])||
            !isset($input['platform']))
            return GeneralTool::createResult('','M00002');

        if(isset($input['message']) && GeneralTool::getcode($input['message']) == '') return GeneralTool::createResult('','M05008');
        if(isset($input['message']) && mb_strlen($input['message']) > 200) return GeneralTool::createResult('','M05063');

        //判断用户是否存在
        if(!$this->orderTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        try{
            //校验商品是否可买
            $input['product_temp_id'] = $this->orderTool->getTemplateByProductId($input['product_id']);

            if(!isset($input['product_temp_id'])) return GeneralTool::createResult('','M08012');

            if(empty($input['quantity'])||!is_numeric($input['quantity'])||$input['quantity']<=0)
                $input['quantity']    = 1;
            else if($input['quantity']>=99)
                $input['quantity']    = 99;
            else
                $input['quantity']    = ceil($input['quantity']);

            $can_buy = $this->orderTool->can_order($input['product_id'], $input['colour_name'], $input['size_name'], $input['quantity'], $input['user_id']);
            if($can_buy['state'] != 'M00000') return $can_buy;
            //校验收货地址编号
            $address = $this->orderTool->addressByID($input['address_id'],$input['user_id']);
            if(!isset($address['result'])||!isset($address['result']->consignee)) return GeneralTool::createResult('','M05006');

            //获取商品详情
            $things = $this->orderTool->get_buy_immediately_submit_goods($input);
            if(!isset($things) || !isset($things['total_fee']) || $things['total_fee'] == 0) return GeneralTool::createResult('','M08012');
            $input['total_fee'] = $things['total_fee'];

            $coupon = isset($input['coupon_id']) && $input['coupon_id'] != '' ? $this->couponsService->getCouponInfoByBuyImmediately($input) : [];
            if(isset($input['coupon_id']) && $input['coupon_id'] != '' && !isset($coupon['discount'])) return GeneralTool::createResult('','M05017');

            if(isset($things['total_fee']) && isset($coupon['discount']) && is_numeric($coupon['discount'])) $things['total_fee'] -= $coupon['discount'] ;

            //生成订单
            $result = $this->orderTool->create_order($things,$input,$address,$coupon);
            if($result['state'] == 'M00000') dispatch((new CreateOrderPush($things, $result, $input))->delay(Carbon::now()->addMinutes(1)));
            //dd($result);
            return $result;

        }catch(\Exception $e){
            Log::info($e);
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        立即购买活动生成订单
        参数:
            user_id         用户编号
            product_id      作品编号
            colour_name     颜色编号
            size_name       尺码
            quantity        数量
            address_id      收货地址编号
            coupon_id       优惠券编号
            platform        平台 IOS Android Web
            message         备注
            channel_id      渠道编号 砍价活动kanjia20170310 七匹狼septwolves20170316
     */
    function create_order_by_buy_immediately_active($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||
            !isset($input['product_id'])||
            !isset($input['colour_name'])||
            !isset($input['size_name'])||
            !isset($input['address_id'])||
            !isset($input['platform']) ||
            !isset($input['channel_id']) ||
            !in_array($input['channel_id'],['kanjia20170310','septwolves20170316']))
            return GeneralTool::createResult('','M00002');

        if(isset($input['message']) && GeneralTool::getcode($input['message']) == '') return GeneralTool::createResult('','M05008');
        if(isset($input['message']) && mb_strlen($input['message']) > 200) return GeneralTool::createResult('','M05063');
        $input['coupon_id'] = '';
        //判断用户是否存在
        if(!$this->orderTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        try{
            //校验商品是否可买
            $input['product_temp_id'] = $this->orderTool->getTemplateByProductId($input['product_id']);

            if(!isset($input['product_temp_id'])) return GeneralTool::createResult('','M08012');


            $input['quantity']    = 1;

            $can_buy = $this->orderTool->can_order_for_activity($input['product_id'], $input['colour_name'], $input['size_name'], $input['quantity'], $input['user_id']);
            if($can_buy['state'] != 'M00000') return $can_buy;

            //校验收货地址编号
            $address = $this->orderTool->addressByID($input['address_id'],$input['user_id']);
            if(!isset($address['result'])||!isset($address['result']->consignee)) return GeneralTool::createResult('','M05006');

            //获取商品详情
            $things = $this->orderTool->get_buy_immediately_submit_goods($input);//dd($things);
            if(!isset($things) || !isset($things['total_fee']) || $things['total_fee'] == 0) return GeneralTool::createResult('','M08012');
            $input['total_fee'] = $things['total_fee'];

            //获取实际活动金额
            $fee     = OrderTool::get_product_fee_active($input);
            if(!isset($fee['product_current_price'])) return GeneralTool::createResult('', 'M05067');
            $things['total_fee'] = $fee['product_current_price'];

            $coupon = isset($input['coupon_id']) && $input['coupon_id'] != '' ? $this->couponsService->getCouponInfoByBuyImmediately($input) : [];
            if(isset($input['coupon_id']) && $input['coupon_id'] != '' && !isset($coupon['discount'])) return GeneralTool::createResult('','M05017');

            if(isset($things['total_fee']) && isset($coupon['discount']) && is_numeric($coupon['discount'])) $things['total_fee'] -= $coupon['discount'] ;

            //生成订单
            $result = $this->orderTool->create_order($things,$input,$address,$coupon,2);
            if($things['total_fee'] == 0 && $result['state'] == 'M00000') OrderTool::order_sync_active($result['result']);
            if($result['state'] == 'M00000') dispatch((new CreateOrderPush($things, $result, $input))->delay(Carbon::now()->addMinutes(1)));
            //dd($result);
            return $result;

        }catch(\Exception $e){
            Log::info($e);
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        全部订单列表
        参数：
            user_id     用户编号
            page        页码
            per_page    每页显示数据量
     */
    function user_order_all($input){
        if(!isset($input['user_id']) ||
            !isset($input['page']) ||
            !isset($input['per_page']) ||
            !is_numeric($input['page']) ||
            !is_numeric($input['per_page'])||
            $input['page'] <= 0||
            $input['per_page'] <= 0)
            return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->orderTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $input['per_page'] = empty($input['per_page']) ? 10 : ceil($input['per_page']);
        $arr['where'] = ['buyer_id' => $input['user_id'],'type' => 'order'];
        $arr['state'] = [1,2,3,4];
        $arr['order'] = 'updated_at';
        $arr['sort']  = 'desc';
        $orders = $this->orderTool->get_order_list($input,$arr);

        return GeneralTool::createResult($orders,'M00000');
    }

    /**
        待支付订单列表
        参数：
            user_id     用户编号
            page        页码
            per_page    每页显示数据量
     */
    function user_order_unpay($input){
        if(!isset($input['user_id']) ||
            !isset($input['page']) ||
            !isset($input['per_page']) ||
            !is_numeric($input['page']) ||
            !is_numeric($input['per_page'])||
            $input['page'] <= 0||
            $input['per_page'] <= 0)
            return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->orderTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $input['per_page'] = empty($input['per_page']) ? 10 : ceil($input['per_page']);
        $arr['where'] = ['buyer_id' => $input['user_id'],
                         'type'     => 'order',
                         'is_cancel'=> 0,
                         'is_aftermark' => 0];
        $arr['state'] = [1];
        $arr['order'] = 'updated_at';
        $arr['sort']  = 'desc';
        $orders = $this->orderTool->get_order_list($input,$arr);

        return GeneralTool::createResult($orders,'M00000');
    }

    /**
        待发货订单列表
        参数：
            user_id     用户编号
            page        页码
            per_page    每页显示数据量
     */
    function user_order_unsend($input){
        if(!isset($input['user_id']) ||
            !isset($input['page']) ||
            !isset($input['per_page']) ||
            !is_numeric($input['page']) ||
            !is_numeric($input['per_page'])||
            $input['page'] <= 0||
            $input['per_page'] <= 0)
            return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->orderTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $input['per_page'] = empty($input['per_page']) ? 10 : ceil($input['per_page']);
        $arr['where'] = ['buyer_id' => $input['user_id'],
                         'type'     => 'order',
                         'is_cancel'=> 0,
                         'is_aftermark' => 0];
        $arr['state'] = [2];
        $arr['order'] = 'updated_at';
        $arr['sort']  = 'desc';
        $orders = $this->orderTool->get_order_list($input,$arr);

        return GeneralTool::createResult($orders,'M00000');
    }

    /**
     * 待收货订单
     * @param  [type] $input [description]
     * @return [type]        [description]
     */
    function user_order_unsign($input){
        if(!isset($input['user_id']) ||
            !isset($input['page']) ||
            !isset($input['per_page']) ||
            !is_numeric($input['page']) ||
            !is_numeric($input['per_page'])||
            $input['page'] <= 0||
            $input['per_page'] <= 0)
            return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->orderTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $input['per_page'] = empty($input['per_page']) ? 10 : ceil($input['per_page']);
        $arr['where'] = ['buyer_id' => $input['user_id'],
                         'type'     => 'order',
                         'is_cancel'=> 0,
                         'is_aftermark' => 0];
        $arr['state'] = [3];
        $arr['order'] = 'updated_at';
        $arr['sort']  = 'desc';
        $orders = $this->orderTool->get_order_list($input,$arr);

        return GeneralTool::createResult($orders,'M00000');
    }

    /**
     * 已完成订单
     * @param  [type] $input [description]
     * @return [type]        [description]
     */
    function user_order_complete($input){
        if(!isset($input['user_id']) ||
            !isset($input['page']) ||
            !isset($input['per_page']) ||
            !is_numeric($input['page']) ||
            !is_numeric($input['per_page'])||
            $input['page'] <= 0||
            $input['per_page'] <= 0)
            return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->orderTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $input['per_page'] = empty($input['per_page']) ? 10 : ceil($input['per_page']);
        $arr['where'] = ['buyer_id' => $input['user_id'],
                         'type'         => 'order',
                         'is_cancel'    => 0];
        $arr['state'] = [4];
        $arr['order'] = 'updated_at';
        $arr['sort']  = 'desc';
        $orders = $this->orderTool->get_order_list($input,$arr);

        return GeneralTool::createResult($orders,'M00000');
    }

    /**
     * 订单详情
        参数：
            user_id         用户编号
            order_id        订单编号
     */
    function order_detail($input){
        //判断参数是否足够
        if(!isset($input['user_id']) || !isset($input['order_id']))
            return GeneralTool::createResult('','M00002');

        $order = $this->orderTool->get_data_from_detail_page($input);

        if(!isset($order->order_id)) return GeneralTool::createResult('','M05022');

        return GeneralTool::createResult($order,'M00000');
    }

    /**
        取消订单
        参数：
            user_id         用户编号
            order_id        订单编号
     */
    function order_cancel($input){
        //判断参数是否足够
        if(!isset($input['user_id']) || !isset($input['order_id']))
            return GeneralTool::createResult('','M00002');
        try{

            $result = $this->orderTool->order_cancel($input);

            $data   = $result == 'M00000' ? $this->orderTool->get_data_from_detail_page($input) : '';
            if($result == 'M00000') OrderTool::cancel_order_success_push($input);
            return $result == 'M00000' ? ['state' => 'M00000', 'result' => $data, 'message' => '取消成功'] :
                                         GeneralTool::createResult('',$result);

        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        查看订单物流
        参数：
            user_id         用户编号
            order_id        订单编号
     */
    function order_express_detail($input){
        if(!isset($input['user_id']) || !isset($input['order_id']))
            return GeneralTool::createResult('','M00002');

        //判断订单是否存在
        if($this->orderTool->get_order_count(['buyer_id' => $input['user_id'],'order_id' => $input['order_id']]) == 0)
            return GeneralTool::createResult('','M05022');

        $order_express                    = $this->orderTool->get_order_expree_info($input['order_id']);
        $order['order_express_id']        = isset($order_express->order_express_id)?$order_express->order_express_id:'';
        $order['express_name']            = isset($order_express->express_name)?$order_express->express_name:'';
        $order['express_id']              = isset($order_express->express_id)?$order_express->express_id:'';
        $order['good_total_quantity']     = $this->orderTool->get_order_good_total_quantity($input['order_id']);
        $order['good_total_quantity_str'] = '共' . $order['good_total_quantity'] . '件商品';
        $images                           = OrderTool::get_order_first_picture($input['order_id']);
        $order['thumbnail']               = isset($images['thumbnail']) ? $images['thumbnail'] : [];
        $order['original_image']          = isset($images['original_image']) ? $images['original_image'] : [];
        $order['express']                 = $this->orderTool->getExpress($order);
        return GeneralTool::createResult($order,'M00000');
    }

    /**
        确认收货
        参数：
            user_id         用户编号
            order_id        订单编号
     */
    function order_sign($input){
        if(!isset($input['user_id']) || !isset($input['order_id']))
            return GeneralTool::createResult('','M00002');

        try{

            $result = OrderTool::order_sign($input);

            $data   = $result == 'M00000' ? $this->orderTool->get_data_from_detail_page($input) : '';
            if($result == 'M00000')  $this->orderTool->sign_order_success_push($input);

            return $result == 'M00000' ? ['state' => 'M00000', 'result' => $data, 'message' => '确认成功'] :
                                         GeneralTool::createResult('',$result);

        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        催单
        参数：
            user_id         用户编号
            order_id        订单编号
     */
    function order_urge($input){
        if(!isset($input['user_id']) || !isset($input['order_id']))
            return GeneralTool::createResult('','M00002');

        //判断订单是否存在
        if($this->orderTool->get_order_count(['buyer_id'     => $input['user_id'],
                                              'order_id'     => $input['order_id'],
                                              'state'        => 2,
                                              'is_cancel'    => 0,
                                              'is_aftermark' => 0]) == 0)
            return GeneralTool::createResult('','M05025');

        //判断今天是否已催单
        $time          = date('Y-m-d',time());
        $input['time'] = strtotime($time);
        if($this->orderTool->orderIsUrge($input)) return GeneralTool::createResult('','M05025');

        $result = $this->orderTool->order_email_by_user_urge($input);

        return $result ? ['state' => 'M00000', 'result' => (object)[], 'message' => '提醒已送达'] :
                         GeneralTool::createResult('', 'M00001');
    }

    /**
        删除订单
        参数：
            user_id         用户编号
            order_id        订单编号
     */
    function order_delete($input){
        if(!isset($input['user_id']) || !isset($input['order_id']))
            return GeneralTool::createResult('','M00002');

        $complete = $this->orderTool->get_order_count(['buyer_id'     => $input['user_id'],
                                                       'order_id'     => $input['order_id'],
                                                       'state'        => 4,
                                                       'is_cancel'    => 0,
                                                       'is_aftermark' => 0]);
        $is_cancel = $this->orderTool->get_order_count(['buyer_id'     => $input['user_id'],
                                                        'order_id'     => $input['order_id'],
                                                        'state'        => 1,
                                                        'is_cancel'    => 1]);

        //判断订单是否存在
        if($complete == 0 && $is_cancel == 0) return GeneralTool::createResult('','M05039');
        try{

            $result = $this->orderTool->order_delete($input, $complete ,$is_cancel);
            if($result != 'M00000') Throw new \Exception('删除订单失败');

            return ['state' => 'M00000', 'result' => (object)[], 'message' => '删除成功'];

        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00001');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
     * 订单绑定工单号
     * 参数：
     *     order_id             订单编号
     *     user_id              用户编号
     *     worksheet_id         工单号
     */
    function orderWorkSheet($input){
        if(!isset($input['worksheet_id']) || !isset($input['order_id']) || !isset($input['user_id']))
            return GeneralTool::createResult('','M00002');

        $result = SQL::pluck(['table' => 'orders',
                              'where' => ['order_id' => $input['order_id'],
                                          'buyer_id'  => $input['user_id']],
                              'pluck' => 'worksheet_id']);
        if(!isset($result) || $result != '') return GeneralTool::createResult('', 'M05064');

        $update = SQL::update(['table'  => 'orders',
                               'where'  => ['order_id' => $input['order_id']],
                               'update' => ['worksheet_id' => $input['worksheet_id']]]);
        return GeneralTool::createResult('', ($update ? 'M00000' : 'M00001'));
    }

    /**
        物流
     */
    /**
        快递100回调
     */
    function expressNotify($input){
        try{
            Log::info('************ 快递100回调 ************');
            Log::info($input);
        }catch(\Exception $e){
            $str = json_encode($input);
            // SQL::insert(array('table'=>'active_logs',
            //                   'insert'=>array('message'=>$str,'created_at'=>time())));
        }
        // if (!isset($input['param'])) return 'fail';
        if (!isset($input['sign']))
            $input['sign'] = '';

        return $this->express->calllBack($input['param'],$input['sign']);
    }

    function test($input){
        $result = OrderTool::order_sync_active($input);
        dd($result);
        return GeneralTool::createResult('','M00000');
    }
}

